package com.wokeMy.view.turui;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.oliveapp.libcommon.utility.LogUtil;
import com.oliveapp.libimagecapture.CaptureImageFragment;
import com.woke.method.MyApp;
import com.wokeMy.view.base.BaseActivity;
import com.wokeMy.view.http.GlideImageLoader;
import com.wokeMy.view.model.Constant;
import com.wokeMy.view.util.BitmapUtil;
import com.wokeMy.view.util.Util;
import com.wokeMy.view.view.SelectDialog;
import com.zhongcai.online.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MyRealNameActivity extends BaseActivity {
    public static final String TAG = MyRealNameActivity.class.getSimpleName();
    private android.widget.ImageView rnameimageback;
    private android.widget.ImageView rnamecanmer;
    private android.widget.TextView rnamecanmertext;
    private android.widget.ImageView rnameidcard;
    private android.widget.RelativeLayout rnamephoto,rnamephotoin;
    private android.widget.LinearLayout rnametext;
    private Button ranemsubmit;
    EditText rnamenametv,rnameidcardtv;
    public static final String EXTRA_IMAGE_CONTENT = "image_content";
    public static final String EXTRA_FACE_EXISTS = "face_exists";
    public static final String EXTRA_FACE_RECT = "face_rect";

    public static final int REQUEST_CODE_SELECT = 100;

    private String user_id;
    private Dialog dialog;
    Bitmap capturedImage;
    File jpeg;
     String name;
     String citizen_id;
    private MyApp myaap;
    /**
     * 存储传回的分析数据
     */
    public static String mResultJsonString;

    public static byte[] verificationData_my;
    @Override
    public void setContentView() {
        setContentView(R.layout.activity_my_real_name);

    }

    @Override
    public void initView() {
        this.rnametext = (LinearLayout) findViewById(R.id.rname_text);
        this.rnamephoto = (RelativeLayout) findViewById(R.id.rname_photo);
        this.rnamephotoin = (RelativeLayout) findViewById(R.id.rname_photo_in);
        this.rnameidcard = (ImageView) findViewById(R.id.rname_idcard);
        this.rnamecanmertext = (TextView) findViewById(R.id.rname_canmer_text);
        this.rnamenametv = (EditText) findViewById(R.id.rname_name_tv);
        this.rnameidcardtv = (EditText) findViewById(R.id.rname_idcard_tv);
        this.rnamecanmer = (ImageView) findViewById(R.id.rname_canmer);
        this.rnameimageback = (ImageView) findViewById(R.id.rname_image_back);
        ranemsubmit=myFindViewById(R.id.ranme_submit);
        ranemsubmit.setEnabled(false);
    }

    @Override
    public void initData() {
        MyApp myApp= (MyApp) getApplication();
        user_id=myApp.getDatas_load().getId();

    }

    @Override
    public void initActivity() {
        rnameimageback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        ranemsubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                name=rnamenametv.getText().toString().trim();
                citizen_id=rnameidcardtv.getText().toString().trim();
                renZhen();
            }
        });
        final List<String> names = new ArrayList<>();
        names.add("拍照");
        names.add("相册");
        rnamephoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(new SelectDialog.SelectDialogListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        switch (position) {
                            case 0: // 直接调起相机
                                if (requestPermission()) {
                                    Intent i = new Intent(MyRealNameActivity.this, SampleImageCaptureActivity.class);
                                    i.putExtra(SampleImageCaptureActivity.EXTRA_CAPTURE_MODE, CaptureImageFragment.CAPTURE_MODE_IDCARD_FRONT);
                                    startActivityForResult(i, Constant.REQUEST_HXKJZF);
                                }
                                break;
                            case 1:
                                ImagePicker imagePicker = ImagePicker.getInstance();
                                imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
                                imagePicker.setShowCamera(false);                      //显示拍照按钮
                                imagePicker.setCrop(false);                           //允许裁剪（单选才有效）
                                imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
                                imagePicker.setSelectLimit(1);              //选中数量限制
                                imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
                                imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
                                imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
                                imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
                                imagePicker.setOutPutY(1000);
                                Intent intent1 = new Intent(MyRealNameActivity.this, ImageGridActivity.class);
                                startActivityForResult(intent1, REQUEST_CODE_SELECT);
                                break;
                            default:
                                break;
                        }

                    }
                }, names);
            }
        });

    }
    ArrayList<ImageItem> images = null;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==Constant.RESPONSE_HXKJZF){
            rnamephotoin.setVisibility(View.GONE);
            rnameidcard.setVisibility(View.VISIBLE);
            Bundle result = data.getExtras();

            final int mode = result.getInt(SampleImageCaptureActivity.EXTRA_CAPTURE_MODE);
            byte[] imageContent = result.getByteArray(EXTRA_IMAGE_CONTENT);
            boolean faceExists = result.getBoolean(EXTRA_FACE_EXISTS);

            capturedImage = BitmapFactory.decodeByteArray(imageContent, 0, imageContent.length);
            if (faceExists) {
                Bitmap imageWithRect = capturedImage.copy(Bitmap.Config.ARGB_8888, true);
                Canvas canvas = new Canvas(imageWithRect);
                Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
                paint.setColor(Color.BLACK);
                paint.setStyle(Paint.Style.STROKE);
                paint.setStrokeWidth(10);
                String rectString = result.getString(EXTRA_FACE_RECT);
                Rect rect = Rect.unflattenFromString(rectString);
                canvas.drawRect(rect, paint);
                rnameidcard.setImageBitmap(imageWithRect);
            } else {
                rnameidcard.setImageBitmap(capturedImage);
            }
            jpeg = BitmapUtil.compressImage(BitmapFactory.decodeByteArray(imageContent, 0, imageContent.length), "jpeg");
            updatePhtoe();
        }else if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                rnamephotoin.setVisibility(View.GONE);
                rnameidcard.setVisibility(View.VISIBLE);
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    ImageItem item = images.get(0);
                    ImagePicker.getInstance().getImageLoader().displayImage(MyRealNameActivity.this, item.path, rnameidcard, 0, 0);
//                    rnameidcard.setImageBitmap(BitmapFactory.decodeFile(item.path));
                    jpeg = BitmapUtil.compressImage(BitmapFactory.decodeFile(item.path), "jpeg");
                    updatePhtoe();
                }
            }
        }else if (resultCode==Constant.RESPONSE_RHLZ){
            Log.e("verificationData_my",""+verificationData_my.length);
            htijian();
        }
    }

 //   **==============================请求相机权限=========================**/
    private static final int PERMISSION_READ_EXTERNAL_STORAGE = 101;
    private static final int PERMISSION_WRITE_EXTERNAL_STORAGE = 102;
    private static final int PERMISSION_CAMERA = 103;
    private boolean requestPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_WRITE_EXTERNAL_STORAGE);
            return false;
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_READ_EXTERNAL_STORAGE);
            return false;
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, PERMISSION_CAMERA);
            return false;
        }

        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        try {
            switch (requestCode) {
                case PERMISSION_CAMERA: {
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    } else {
                        Toast.makeText(this, "没有摄像头权限我什么都做不了哦!", Toast.LENGTH_LONG).show();
                    }
                    break;
                }
                case PERMISSION_READ_EXTERNAL_STORAGE: {
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    } else {
                        Toast.makeText(this, "请打开存储读写权限，确保APP正常运行", Toast.LENGTH_LONG).show();
                    }
                    break;
                }
                case PERMISSION_WRITE_EXTERNAL_STORAGE: {
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    } else {
                        Toast.makeText(this, "请打开存储读写权限，确保APP正常运行", Toast.LENGTH_LONG).show();
                    }
                    break;
                }
            }
        } catch (Exception e) {
            LogUtil.e(TAG, "Failed to request Permission", e);
        }
    }
    private SelectDialog showDialog(SelectDialog.SelectDialogListener listener, List<String> names) {

        SelectDialog dialog = new SelectDialog(this, R.style
                .transparentFrameWindowStyle,
                listener, names);
        if (!this.isFinishing()) {
            dialog.show();
        }
        return dialog;
    }
    public void updatePhtoe(){
        OkGo.<String>post(Constant.UPIDCARD_URL)//
                .tag(this)//
                .cacheMode(CacheMode.NO_CACHE)//
                .cacheKey("no_cache")   //对于无缓存模式,该参数无效
                .cacheTime(5000)        //对于无缓存模式,该时间无效
                .params("user_id", user_id)//
                .params("file1",jpeg)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Util.closeDialog(dialog);
                        try {
                            JSONObject jsonObject =new JSONObject(response.body());
                            name = jsonObject.getJSONObject("data").getJSONObject("data").getString("name");
                            citizen_id = jsonObject.getJSONObject("data").getJSONObject("data").getString("citizen_id");
                            if (name.equals("")){
                                tishi("请上传正确的身份证正面照");
                            }else {
                                tishiToast("上成功");
                                ranemsubmit.setEnabled(true);
                                ranemsubmit.setBackgroundResource(R.drawable.rname_biankuang_check);
                                rnametext.setVisibility(View.VISIBLE);
                                rnamenametv.setText(name);
                                rnameidcardtv.setText(citizen_id);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        dialog= Util.createLoadingDialog(MyRealNameActivity.this,"上传中");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Util.closeDialog(dialog);
                        tishiToast("上传失败");
                    }
                });
    }
    public void renZhen(){
        OkGo.<String>post(Constant.EYIDCARD_URL)//
                .tag(this)//
                .cacheMode(CacheMode.NO_CACHE)//
                .cacheKey("no_cache")   //对于无缓存模式,该参数无效
                .cacheTime(5000)        //对于无缓存模式,该时间无效
                .params("user_id", user_id)//
                .params("nicename",name)
                .params("userno",citizen_id)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Util.closeDialog(dialog);
                        try {
                            JSONObject jsonObject =new JSONObject(response.body());
                            String info = jsonObject.getString("info");
                            if (jsonObject.getString("flag").equals("success")){
                                new AlertView("提示", info, null, new String[]{"确定"}, null, MyRealNameActivity.this, AlertView.Style.Alert, new OnItemClickListener() {
                                    @Override
                                    public void onItemClick(Object o, int i) {
                                        if(requestPermission()){
                                            Intent intent=new Intent(MyRealNameActivity.this,SampleLivenessActivity.class);
                                            startActivityForResult(intent,Constant.REQUEST_RHLZ);
                                        }
                                    }
                                }).show();

                            }else {
                                tishi(info);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        dialog= Util.createLoadingDialog(MyRealNameActivity.this,"上传中");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Util.closeDialog(dialog);
                        tishi("认证失败");
                    }
                });
    }
    public void htijian(){
        OkGo.<String>post(Constant.HTJIANCH_URL)//
                .tag(this)//
                .cacheMode(CacheMode.NO_CACHE)//
                .cacheKey("no_cache")   //对于无缓存模式,该参数无效
                .cacheTime(5000)        //对于无缓存模式,该时间无效
                .params("user_id", user_id)//
                .params("query_image_package",android.util.Base64.encodeToString(verificationData_my, android.util.Base64.NO_WRAP))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Util.closeDialog(dialog);
                        try {
                            JSONObject jsonObject =new JSONObject(response.body());
                            String info = jsonObject.getString("info");
                            if(jsonObject.getString("flag").equals("success")){
                              tishiToast(info);
                                myaap= (MyApp) getApplication();
                                if (myaap.getDatas_load () != null) {
                                    myaap.getDatas_load ().setUser_no_status ("3");
                                }
                                setResult (122);
                                finish ();
                            }else {
                                tishi(info);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        dialog= Util.createLoadingDialog(MyRealNameActivity.this,"上传中");
                    }
                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Util.closeDialog(dialog);
                        tishi("活体检测失败");
                    }
                });
    }
}
